package com.shop.shoporder.wapController;

import com.alibaba.fastjson.JSONObject;
import com.shop.shoporder.common.MessageConstants;
import com.shop.shoporder.common.Response;
import com.shop.shoporder.common.StringUtil;
import com.shop.shoporder.common.TokenUtils;
import com.shop.shoporder.entity.*;
import com.shop.shoporder.service.GroupbuyFinaceService;
import com.shop.shoporder.service.GroupbuyGoodService;
import com.shop.shoporder.service.GroupbuyParticipateService;
import com.shop.shoporder.service.GroupbuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin
@Controller
@RequestMapping("/wap")
public class GroupbuyController {


    @Autowired
    GroupbuyGoodService groupbuyGoodService;
    @Autowired
    GroupbuyService groupbuyService;
    @Autowired
    GroupbuyFinaceService groupbuyFinaceService;
    @Autowired
    GroupbuyParticipateService groupbuyParticipateService;


    //发起团购活动
    @Transactional
    @ResponseBody
    @RequestMapping("/initiateGroupbuy")
    public Response initiateGroupbuy(HttpServletRequest request) {
        //发起的条件
        int groupbuygoodId = 0;
        int goodCount = 0;

        //产品购买数量
        String buycounts = null;
        int buycount = 0;
        double groupbuyPrice = 0.00;
        buycounts = request.getParameter("buycount");
        if (buycounts != null && !"".equalsIgnoreCase(buycounts)) {
            buycount = Integer.parseInt(buycounts);
        }
        //（1）验证登录
        int userNoId = 0;
        String token = request.getHeader("token");
        if (token == null || token == "") {//未登录
            return new Response(MessageConstants.MSG_NO_LOGIN, null, 0, "", request);
        } else {

//            userNoId = TokenUtils.getUserNoId(token);
            userNoId = 91864;

        }
        //（1）用户必须是店主以上的等级
        int rankId = 0;
        String no = null;
        String nick = null;
        String headPic = null;
        Timestamp groupbuyGoodEndTime = null;
        RestTemplate restTemplate = new RestTemplate();
        String url = HttpRequestConfig.userServerUrl + "/wap/getNoInfo?";
//        String url = "http://localhost:8083/wap/getUsernoInfo?";
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("userNoId", userNoId + "");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(map, headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);
        String str = resp.toString();
        String subStr = str.substring(str.indexOf("{"), str.lastIndexOf("}") + 1);
        System.out.println(subStr);
        JSONObject strObj = JSONObject.parseObject(subStr);
        if (strObj != null) {
            JSONObject dataObj = JSONObject.parseObject(strObj.get("data").toString());
            if (dataObj != null) {
                //等级
                if (dataObj.get("rankId") != null && dataObj.get("rankId") != "") {
                    rankId = Integer.parseInt(dataObj.get("rankId").toString());
                }
                //用户编号
                if (dataObj.get("no") != null && dataObj.get("no") != "") {
                    no = dataObj.get("no").toString();
                }

                //用户昵称
                if (dataObj.get("nick") != null && dataObj.get("nick") != "") {
                    nick = dataObj.get("nick").toString();
                }

                //用户昵称
                if (dataObj.get("headPic") != null && dataObj.get("headPic") != "") {
                    headPic = dataObj.get("headPic").toString();
                }

            }
        }

        if (rankId < 3) {
            return new Response(MessageConstants.UNRANK, null, 0, "", request);
        }

        //(2)产品数量必须在产品限量
        String groupbuygoodIds = request.getParameter("groupbuygoodId");
        if (groupbuygoodIds != null && groupbuygoodIds != "") {
            groupbuygoodId = Integer.parseInt(groupbuygoodIds);
        }
        GroupbuyGood groupbuyGood = null;
        groupbuyGood = groupbuyGoodService.selectByPrimaryKey(groupbuygoodId);
        if (groupbuyGood != null) {
            goodCount = groupbuyGood.getGoodsCount();
            groupbuyPrice = groupbuyGood.getGroupbyPrice();
            groupbuyGoodEndTime = new Timestamp(groupbuyGood.getEndTime().getTime());
            if (goodCount < 1) {
                return new Response(MessageConstants.UNGROUPBUYGOODCOUNT, null, 0, "", request);
            }
        }
        //(3)发起团购的团购数量为产品数量的1/10
        List<Groupbuy> groupbuyList = groupbuyService.getGroupbuyCount(groupbuygoodId);
        if (groupbuyList.size() >= goodCount / 10) {
            return new Response(MessageConstants.MAX_GROUPBUY_COUNT, null, 0, "", request);
        }
        //（4）同一个产品一个人只发起一个团购
        Timestamp groupbuyEndtime = null;
        Groupbuy groupbuy = groupbuyService.getGroupbuyByUserNoId(userNoId, groupbuygoodId);
        if (groupbuy != null) {
            groupbuyEndtime = groupbuy.getGroupbuyEndtime();
            return new Response(MessageConstants.GOODS_GROUPBUY_COUNT, null, 0, "", request);
        }

        //（5）组团是否能达到组团的最低要求，如果达不到则需要间隔15天以后才能再次发起团购
        int groupbuyCount = 0;
        GroupbuyFinace groupbuyFinace = groupbuyFinaceService.selectByPrimaryKey(1);
        if (groupbuyFinace != null) {
            groupbuyCount = groupbuyFinace.getGroupbuyCount();
        }
        List<Participater> participaterList = new ArrayList<>();

        List<GroupbuyInfo> groupbuyInfoList = groupbuyService.getGroupbuyListByUserNoId(userNoId);
        if (groupbuyInfoList != null && groupbuyInfoList.size() > 0) {
            for (int i = 0; i < groupbuyInfoList.size(); i++) {
                participaterList = groupbuyInfoList.get(i).getParticipaters();//参团人数
            }

            if (participaterList.size() < groupbuyCount) {//发起团购不达标的
                Date date = new Date();
                Date date3 = groupbuyEndtime;
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm.SSS");
                String date1 = df.format(date);
                String date2 = null;
                if (date3 != null) {
                    date2 = df.format(date3);

                    Date d2 = null;
                    Date d1 = null;
                    try {
                        d1 = df.parse(date1);
                        d2 = df.parse(date2);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if ((d1.getTime() - d2.getTime()) / (24 * 60 * 60 * 1000) < 15) {
                        return new Response(MessageConstants.UNGROUPBUY_STAND, null, 0, "", request);
                    }

                }


            }
        }


        //团购条件都满足，则可以发起团购
        Groupbuy groupbuy1 = null;
        groupbuy1 = groupbuyService.getGroupbuyByUserNoId(userNoId, groupbuygoodId);
        Groupbuy groupbuy2 = new Groupbuy();
        groupbuy2.setInitiateStarttime(new Timestamp(System.currentTimeMillis()));
        groupbuy2.setGroupbuygoodId(groupbuygoodId);
        groupbuy2.setGroupbuyState("1");
        groupbuy2.setInitiateState("0");//0发起未支付状态 1发起已支付成功状态
        groupbuy2.setSort(100);
        groupbuy2.setUserNick(nick);
        groupbuy2.setUserNo(no);
        groupbuy2.setHeadPic(headPic);
        groupbuy2.setUserNoId(userNoId);
        groupbuy2.setGroupbuyEndtime(groupbuyGoodEndTime);//团购结束时间
        groupbuy2.setBuycount(buycount);
        groupbuy2.setGroupbuyPrice(groupbuyPrice);
        int row = 0;
        if (groupbuy1 != null) {//更新
            groupbuy2.setGroupbuyId(groupbuy1.getGroupbuyId());
            row = groupbuyService.updateByPrimaryKeySelective(groupbuy2);
        } else {
            row = groupbuyService.insertSelective(groupbuy2);

        }
        if (row > 0) {
            //减团购产品的数量
            minusGroupbuyGoodCount(groupbuygoodId, goodCount);
            return new Response(MessageConstants.MSG_SUCCESS, groupbuy2, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
        }

    }


    //参与团购
    @ResponseBody
    @RequestMapping("/participateGroupbuy")
    public Response participateGroupbuy(HttpServletRequest request) {
        Map<String, Object> responseMap = new HashMap<>();

        //产品购买数量
        String buycounts = null;
        int buycount = 0;
        double groupbuyPrice = 0.00;
        buycounts = request.getParameter("buycount");
        if (buycounts != null && !"".equalsIgnoreCase(buycounts)) {
            buycount = Integer.parseInt(buycounts);
        }

        //(1)用户登录
        int userNoId = 0;
        Groupbuy groupbuy = null;
        int groupbuyId = 0;
        String no = null;
        String nick = null;
        String headPic = null;
        String token = request.getHeader("token");
        if (token == null || "".equalsIgnoreCase(token)) {//未登录
            return new Response(MessageConstants.MSG_NO_LOGIN, null, 0, "", request);
        } else {

            userNoId = TokenUtils.getUserNoId(token);

            RestTemplate restTemplate = new RestTemplate();
            String url = HttpRequestConfig.userServerUrl + "/wap/getNoInfo?";
//            String url = "http://127.0.0.1:8083/wap/getUsernoInfo?";
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("userNoId", userNoId + "");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(map, headers);
            ResponseEntity<String> resp = restTemplate.postForEntity(url, req, String.class);
            String str = resp.toString();
            String subStr = str.substring(str.indexOf("{"), str.lastIndexOf("}") + 1);
            System.out.println(subStr);
            JSONObject strObj = JSONObject.parseObject(subStr);
            if (strObj != null) {
                JSONObject dataObj = JSONObject.parseObject(strObj.get("data").toString());
                if (dataObj != null) {

                    //用户编号
                    if (dataObj.get("no") != null && dataObj.get("no") != "") {
                        no = dataObj.get("no").toString();
                        System.out.println("no:" + no);
                    }

                    //用户昵称
                    if (dataObj.get("nick") != null && dataObj.get("nick") != "") {
                        nick = dataObj.get("nick").toString();
                        System.out.println("nick:" + nick);
                    }

                    //用户头像
                    if (dataObj.get("headPic") != null && dataObj.get("headPic") != "") {
                        headPic = dataObj.get("headPic").toString();
                        System.out.println("headPic:" + headPic);
                    }

                }
            }

        }

        //(2)产品数量必须在产品限量
        int groupbuygoodId = 0;
        int goodCount = 0;
        int goodId = 0;
        int specId = 0;
        String groupbuygoodIds = request.getParameter("groupbuygoodId");
        if (groupbuygoodIds != null && groupbuygoodIds != "") {
            groupbuygoodId = Integer.parseInt(groupbuygoodIds);
        }

        GroupbuyGood groupbuyGood = null;
        groupbuyGood = groupbuyGoodService.selectByPrimaryKey(groupbuygoodId);
        if (groupbuyGood != null) {
            goodId = groupbuyGood.getGoodsId();
            goodCount = groupbuyGood.getGoodsCount();
            groupbuyPrice = groupbuyGood.getGroupbyPrice();
            if (goodCount < 1) {
                return new Response(MessageConstants.UNGROUPBUYGOODCOUNT, null, 0, "", request);
            }
        }

        //产品的信息及规格列表
        List<GroupbuyGood> groupbuyGoodList = null;
        if (goodId != 0) {
            groupbuyGoodList = groupbuyGoodService.getGroupbuyGoodListByGoodId(goodId);
        }


        String groupbuyIds = request.getParameter("groupbuyId");
        if (groupbuyIds != null && groupbuygoodIds != "") {
            groupbuyId = Integer.parseInt(groupbuyIds);
        }


        //参与团购
        GroupbuyParticipate groupbuyParticipate = new GroupbuyParticipate();
        groupbuyParticipate.setGroupbuyId(groupbuyId);
        groupbuyParticipate.setParticipateEndstate("1");
        groupbuyParticipate.setParticipateStarttime(new Timestamp(System.currentTimeMillis()));
        groupbuyParticipate.setParticipateSort(100);
        groupbuyParticipate.setUserNick(nick);
        groupbuyParticipate.setUserNo(no);
        groupbuyParticipate.setHeadPic(headPic);
        groupbuyParticipate.setUserNoId(userNoId);
        groupbuyParticipate.setParticipateEndtime(groupbuyGood.getEndTime());
        groupbuyParticipate.setParticipateState("0");//0参与未支付 1参与已支付成功
        groupbuyParticipate.setBuycount(buycount);
        groupbuyParticipate.setGroupbuyPrice(groupbuyPrice);
        //查询用户是否参与过
        int row = 0;
        GroupbuyParticipate groupbuyParticipate1 = null;
        groupbuyParticipate1 = groupbuyParticipateService.getGroupbuyPartied(groupbuyId, userNoId);
        if (groupbuyParticipate1 != null) {
            groupbuyParticipate.setParticipateId(groupbuyParticipate1.getParticipateId());
            row = groupbuyParticipateService.updateByPrimaryKeySelective(groupbuyParticipate);
        } else {
            row = groupbuyParticipateService.insertSelective(groupbuyParticipate);
        }

        if (row > 0) {
            //减团购产品的数量
            minusGroupbuyGoodCount(groupbuygoodId, goodCount);
            return new Response(MessageConstants.MSG_SUCCESS, groupbuyParticipate, 0, "", request);
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
        }


    }

    /**
     * 发起或是参与成功，减去产品的库存的数量
     * @param groupbuygoodId
     * @param goodCount
     */
    private void minusGroupbuyGoodCount(int groupbuygoodId, int goodCount) {
        GroupbuyGood groupbuyGood1 = new GroupbuyGood();
        groupbuyGood1.setGroupbuygoodId(groupbuygoodId);
        groupbuyGood1.setGoodsCount(goodCount - 1);
        int row1 = 0;
        row1 = groupbuyGoodService.updateByPrimaryKeySelective(groupbuyGood1);
    }

    /**
     * 获取团购发起人和参与团购人的信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getGroupbuyAndParticpaterInfo")
    public Response getGroupbuyAndParticpaterInfo(HttpServletRequest request) {
        int groupbuyId = 0;
        String groupbuyIds = request.getParameter("groupbuyId");
        if (groupbuyIds != null && groupbuyIds != "" && !StringUtil.isNumeric(groupbuyIds)) {
            groupbuyId = Integer.parseInt(groupbuyIds);
        }
        List<GroupbuyInfo> groupbuyInfoList = null;
        if (groupbuyId != 0) {
            groupbuyInfoList = groupbuyService.getGroupbuyAndParticpaterInfo(groupbuyId);
        }
        return new Response(MessageConstants.MSG_SUCCESS, groupbuyInfoList, 0, "", request);

    }


    //修改团购的状态
//    @ResponseBody
//    @RequestMapping("/updateGroupbuyStatus")
//    public Response updateGroupbuyStatus(HttpServletRequest request) {
//        //(1)、团主修改
//        int participateId = 0;
//        int groupbuyId = 0;
//        String groupbuyIds = null;
//        String participateIds = null;
//        groupbuyIds = request.getParameter("groupbuyId");
//        participateIds = request.getParameter("participateId");
//
//        if (groupbuyIds != null && "".equals(groupbuyIds) && StringUtil.isNumeric(groupbuyIds)) {
//            groupbuyId = Integer.parseInt(groupbuyIds);
//        }
//
//        if (participateIds != null && "".equals(participateIds) && StringUtil.isNumeric(participateIds)) {
//            participateId = Integer.parseInt(participateIds);
//        }
//
//
//        if (groupbuyId != 0) {
//            Groupbuy groupbuy = new Groupbuy();
//            //   groupbuy.setGroupbuyState("1");//0未支付，1已支付
//            groupbuy.setInitiateState("1");
//            groupbuy.setGroupbuyId(groupbuyId);
//            //修改
//            int row = 0;
//            row = groupbuyService.updateByPrimaryKeySelective(groupbuy);
//            if (row > 0) {
//                return new Response(MessageConstants.MSG_SUCCESS, groupbuy, 0, "", request);
//            } else {
//                return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
//            }
//        } else if (participateId != 0) {  //（2）、参与者修改
//
//            GroupbuyParticipate groupbuyParticipate = new GroupbuyParticipate();
//            groupbuyParticipate.setParticipateState("1");
//            groupbuyParticipate.setParticipateId(participateId);
//            //修改
//            int row1 = 0;
//            row1 = groupbuyParticipateService.updateByPrimaryKeySelective(groupbuyParticipate);
//            if (row1 > 0) {
//                return new Response(MessageConstants.MSG_SUCCESS, groupbuyParticipate, 0, "", request);
//            } else {
//                return new Response(MessageConstants.MSG_SYS_ERROR, null, 0, "", request);
//            }
//        } else {
//            //两个参数都为空
//            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT, null, 0, "", request);
//        }
//    }


}
